package com.cuckoo.cuckoo_app2.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.adapters.WalletTradeAdpter;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.WalletAPiImp;
import com.cuckoo.cuckoo_app2.apiAsync.WalletApi;
import com.cuckoo.cuckoo_app2.dao.ItemWallet;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.dao.WalletaMnagement;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.RouteUtils;
import com.cuckoo.cuckoo_app2.utils.ScreenUtils;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WalletActivity extends AppCompatActivity {

    private ViewHolder holder;
    private Context context;
    private RecyclerView recyclerView;
    private WalletTradeAdpter adpter;
    private List<ItemWallet> dataList = new ArrayList<>();
    private WalletApi walletApi;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private WalletaMnagement walletaMnagement;
    private Integer pageNo = 1;
    private Integer pageSize = 20;
    private boolean isLoading = false;
    private int heightPixels;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet);
        this.context = this;
        this.walletApi = new WalletAPiImp();
        this.holder = new ViewHolder();

        // 获取屏幕高度
        heightPixels = ScreenUtils.getScreenHeight(getWindowManager());


        // 初始化 RecyclerView
        recyclerView = findViewById(R.id.lv_trade_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 初始化适配器并设置给 RecyclerView
        adpter = new WalletTradeAdpter(this, dataList);
        recyclerView.setAdapter(adpter);

        // 当数据大于20条时才显示
        holder.show_more.setVisibility(View.GONE);
        recyclerView.setVisibility(View.GONE);

        // 提现事件
        holder.btn_withdraw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RouteUtils.toWithdrawActivity(context);
            }
        });

        // 显示更多
        holder.show_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLoading) {
                    DialogUtils.showToast(context, "正在加载中");
                    return;
                }
                pageNo += 1;
                getData();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        pageNo = 1;
        dataList = new ArrayList<>();
        // 获取钱包信息
        getWallet();
        // 获取数据
        getData();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 获取钱包信息
     */
    public void getWallet() {
        User user = MyApplication.instances.getUser();

        walletApi.performGetWalletAsync(user.getId(), new BaseCallbac<JsonObject>() {

            @Override
            public void onSuccess(JsonObject data) {
                // 视图
                runOnUiThread(() -> {
                    if (!data.get("success").getAsBoolean()) {
                        DialogUtils.showToast(context, data.get("message").getAsString());
                        return;
                    }
                    JsonObject result = data.get("result").getAsJsonObject();
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                    walletaMnagement = gson.fromJson(result, WalletaMnagement.class);

                    // 渲染页面
                    holder.tv_balance.setText(walletaMnagement.getBalance().toString());
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                runOnUiThread(() -> {
                    DialogUtils.showToast(context, errorMessage);
                });
            }
        });

    }

    public void getData() {
        User user = MyApplication.instances.getUser();
        HashMap<String, String> params = new HashMap<String, String>() {{
            put("accountId", user.getId());
            put("pageNo", pageNo.toString());
            put("pageSize", pageSize.toString());
            put("column", "createTime");
            put("order", "desc");
        }};
        isLoading = true;
        walletApi.performGetWalletListAsync(params, new BaseCallbac<JsonObject>() {
            @Override
            public void onSuccess(JsonObject data) {
                isLoading = false;
                runOnUiThread(() -> {
                    if (!data.get("success").getAsBoolean()) {
                        DialogUtils.showToast(context, data.get("message").getAsString());
                        return;
                    }
                    JsonObject result = data.get("result").getAsJsonObject();
                    int total = result.get("total").getAsInt();
                    if (total <= 0) {
                        return;
                    }
                    recyclerView.setVisibility(View.VISIBLE);

                    JsonArray records = result.get("records").getAsJsonArray();
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                    ItemWallet itemWallet;
                    JsonObject record;
                    for (int i = 0; i < records.size(); i++) {
                        record = records.get(i).getAsJsonObject();
                        itemWallet = gson.fromJson(record, ItemWallet.class);
                        dataList.add(itemWallet);
                    }
                    ScreenUtils.showMore(context, recyclerView, dataList.size(), 87);
                    // 是否显示更多
                    int showMore = ScreenUtils.isShowMore(total, pageSize, pageNo);
                    holder.show_more.setVisibility(showMore);
                    // 更新列表
                    adpter.updateData(dataList);
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                isLoading = false;
                runOnUiThread(() -> {
                    DialogUtils.showToast(context, errorMessage);
                });
            }
        });

    }

    /**
     * 获取相应的ID
     */
    class ViewHolder {
        MaterialButton btn_withdraw;
        TextView tv_balance;
        MaterialButton show_more;

        public ViewHolder() {
            btn_withdraw = findViewById(R.id.btn_withdraw);
            tv_balance = findViewById(R.id.tv_balance);
            show_more = findViewById(R.id.w_show_more);
        }
    }


}
